package coml.allen.api.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * @author sesshomaru
 * @date 2020/11/14 16:23
 */
public class Producer {

    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("192.168.1.102");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 开启消息发送确认
        channel.confirmSelect();

        String exchange = "test_confirm_ex";
        String routingKey = "confirm.save";

        String msg = "this is producer test confirm msg";
        channel.basicPublish(exchange, routingKey, null, msg.getBytes());

        // 添加确认监听
        channel.addConfirmListener(new ConfirmListener() {
            // 发送到broker(exchange)上成功的时候进入此方法
            // deliveryTag 消息的唯一标签 multiple
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("--------------- ack --------------");
            }

            // 发送到broker(exchange)上失败的时候进入此方法
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("--------------- no ack --------------");
            }
        });
    }
}
